$(document).ready(function(){
	// 定义变量
	let search = {
		pageNo: 1,
		pageSize: 10
	};
	
	// 导入模块
	const api = require("./modules/api.js");
	const url = require("url");
	const querystring = require("querystring");
	const moment = require("moment");
	
	// 导入nunjucks
	const env = new nunjucks.Environment(new nunjucks.WebLoader('/views'));
	
	// 添加过滤器
	env.addFilter("formatDateTime", (timestamp, template)=>{
    	return moment(timestamp).format(template);
	});

	env.addFilter("formatType", (type)=>{
	    switch(type){
	        case "TP":
	            return "贴牌";
	        case "PF":
	            return "批发";
	        default:
	            return type;
	    }
	});
	env.addFilter("formatTradeType", (tradeType)=>{
	    switch(tradeType){
	        case "ONLINE":
	            return "在线担保交易";
	        case "OFFLINE":
	            return "线下担保交易";
	    }
	});
	env.addFilter("formatPayStatus", (payStatus)=>{
	    switch(payStatus){
	        case true:
	            return "已支付";
	        case false:
	            return "待支付";
	    }
	});


	// 获取表格模版
	const table_temp = env.getTemplate("order_list.html");
	// 获取分页模版
	const pagination_temp = env.getTemplate("pagination.html");

	// 监测订单类型变化
	$("#type").change(function(e){
		handleSearch();
	});
	// 监测订单状态变化
	$("#status").change(function(e){
		handleSearch();
	});
	
	function handleSearch(){
		search = {
			pageNo: 1,
			pageSize: 10,
			type: $("#type").val(),
			status: $("#status").val()
		};
		getList();
	};
	
	// 获取列表
	function getList(){
		api.order_list(search).then(res=>{
			console.log(res);
			if(res.code == "0"){
				let list = res.result.list || [];
				let page = res.result.page;
				let pageNo = search.pageNo;
				let base_url = window.location.path;

				table_render(list);
				pagination_render(page, base_url, pageNo);
			};
		});
	};

	// 渲染表格
	function table_render(list){
		table_temp.render({list}, (err, html)=>{
			// console.log(err);
			// console.log(html);
			$("#table").empty().append(html);
		});
	};

	// 渲染分页
	function pagination_render(page, base_url, pageNo){
		pagination_temp.render({page, base_url, pageNo}, (err, html)=>{
			// console.log(err);
			// console.log(html);
			$("#pagination").empty().append(html);
		});
	};
	
	// 分页
	$("#pagination").click(function(e){
		e.preventDefault();
		let target = e.target;
		let href = target.href;
		if(href){
			console.log(href);
			let query = url.parse(href).query;
			let pageNo = querystring.parse(query).pageNo;
			
			search.pageNo = pageNo;

			getList();
		};
		
	});
});